package com.huluobo.a2202mvvm_im_douyindemo;

import android.app.ActivityManager;
import android.app.Application;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.TaskStackBuilder;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.media.SoundPool;
import android.os.Bundle;
import android.util.Log;

import com.huluobo.a2202mvvm_im_douyindemo.chat.ChatActivity;
import com.huluobo.a2202mvvm_im_douyindemo.db.AppDBUtils;
import com.hyphenate.EMMessageListener;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMMessage;
import com.hyphenate.chat.EMOptions;
import com.hyphenate.chat.EMTextMessageBody;
import com.hyphenate.easeui.EaseIM;
import com.umeng.commonsdk.UMConfigure;
import com.umeng.socialize.PlatformConfig;
import com.uuzuche.lib_zxing.activity.ZXingLibrary;

import java.util.List;

/**
 * Created by LC on 2024/4/19.
 */
public class IMApp extends Application {

    //3-20位字符,首字符必须为英文
    public static final String REGEX_USERNAME = "^[a-zA-Z]\\w{2,19}$";

    //3-20位数字
    public static final String REGEX_PASSWORD = "^[0-9]{3,20}$";

    //声音池,类似于线程池,
    private SoundPool soundPool = new SoundPool.Builder().setMaxStreams(10).build();

    //处于前台播放的声音的id
    private int duan;
    //处于后台播放的声音的id
    private int yulu;

    @Override
    public void onCreate() {
        super.onCreate();
        EMOptions options = new EMOptions();
        options.setAppKey("moroks#2202mvvmimdouyindemo");
//        EMClient.getInstance().init(this, options);

        //EaseIM 初始化
        if (EaseIM.getInstance().init(this, options)) {
            //在做打包混淆时，关闭 debug 模式，避免消耗不必要的资源
            EMClient.getInstance().setDebugMode(true);
            //EaseIM 初始化成功之后再调用注册消息监听的代码 ...
        }

        //二维码的初始化
        ZXingLibrary.initDisplayOpinion(this);

        //友盟初始化
        UMConfigure.init(this, "663b35d5940d5a4c4950f692"
                , "umeng", UMConfigure.DEVICE_TYPE_PHONE, "");
        // QQ设置
        PlatformConfig.setQQZone("101830139", "5d63ae8858f1caab67715ccd6c18d7a5");

        //数据库初始化
        AppDBUtils.getInstance().init(this);

        //添加全局消息监听器
        EMClient.getInstance().chatManager().addMessageListener(messages -> {
            if (isForeground()) {
                //处于前台位置,不弹通知
                soundPool.play(duan, 1, 1, 0, 0, 1);
            } else {
                soundPool.play(yulu, 1, 1, 0, 0, 1);
                NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
                for (int i = 0; i < messages.size(); i++) {
                    String contentText = "消息内容";
                    if (messages.get(i).getType() == EMMessage.Type.TXT) {
                        contentText = ((EMTextMessageBody) messages.get(i).getBody()).getMessage();
                    } else if (messages.get(i).getType() == EMMessage.Type.IMAGE) {
                        contentText = "[图片]";
                    } else if (messages.get(i).getType() == EMMessage.Type.FILE) {
                        contentText = "[文件]";
                    } else {
                        contentText = "其他消息";
                    }

                    Intent intent = new Intent(this, ChatActivity.class);
                    Bundle bundle = new Bundle();
                    bundle.putString("conversationId", messages.get(i).conversationId());

                    if (messages.get(i).getChatType() == EMMessage.ChatType.Chat) {
                        bundle.putInt("chatType", 1);
                    } else if (messages.get(i).getChatType() == EMMessage.ChatType.GroupChat) {
                        bundle.putInt("chatType", 2);
                    }

                    intent.putExtras(bundle);
                    //通过任务栈,(addParentStack)先打开ChatActivity的父Activity(MainActivity)
                    // ,(.addNextIntent(intent);)再打开ChatActivity的intent
                    TaskStackBuilder taskStackBuilder =
                            TaskStackBuilder.create(this).addParentStack(ChatActivity.class).addNextIntent(intent);
                    PendingIntent pendingIntent = taskStackBuilder.getPendingIntent(0,
                            PendingIntent.FLAG_UPDATE_CURRENT);

//                    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent,
//                            PendingIntent.FLAG_UPDATE_CURRENT);

                    Notification notification = new Notification.Builder(this)
                            .setContentTitle("收到新消息")
                            .setContentText(contentText)
                            .setSmallIcon(R.mipmap.ic_launcher)//状态栏小图标 ******注意,必须要有,否则通知没效果******
                            .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.huoying))
                            .setAutoCancel(true)
                            .setContentIntent(pendingIntent)
                            .build();

                    notificationManager.notify(1, notification);

                }
            }
        });

        //初始化声音,实例2个声音 上下文 资源文件id,线程优先级
        duan = soundPool.load(this, R.raw.duan, 0);
        yulu = soundPool.load(this, R.raw.yulu, 0);
    }

    //判断当前app处于前台还是后台的位置
    private boolean isForeground() {
        ActivityManager activityManager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
        //循环当前手机中正在运行的app的进程信息
        //ActivityManager.RunningAppProcessInfo 正在运行的app的进程信息
        //runningAppProcessInfo.importance  当前金城的优先级
        //IMPORTANCE_FOREGROUND 优先级处于前台的位置
        for (ActivityManager.RunningAppProcessInfo runningAppProcessInfo : activityManager.getRunningAppProcesses()) {
            //对比当前运行的app的有限制是否等于前台的优先级,如果等于就说明当前app运行在前台,如果不等于,就代表运行在后台
            return runningAppProcessInfo.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND;
        }
        return false;
    }
}
